<template>
  <div class="charts">
    <div id="charts" ref="charts"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: "BaseEcharts",
  props: {
    // 图表参数
    options: {
      type: Object,
    },
  },
  data() {
    return {
      myChart: null,
    };
  },
  watch: {
    // 深入监听数据改变
    options: {
      handler(newValue, oldValue) {
        this._initECharts(newValue);
      },
      deep: true,
    },
  },
  mounted() {
    this._initECharts(this.options);
  },
  destroyed() {
    if (this.myChart) {
      this.myChart.clear();
    }
  },
  methods: {
    /**
     * 初始化ECharts
     * @param options
     * @private
     */
    _initECharts(options) {
      try {
        const _this = this;
        // 后续更新数据不需要重新init
        if (!this.myChart) this.myChart = echarts.init(this.$refs.charts);
        this.myChart.setOption(options);
        window.addEventListener("resize", function () {
          _this.myChart.resize();
        });
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.charts {
  width: 100%;
  height: 100%;
  #charts {
    width: 100%;
    height: 100%;
  }
}
</style>
